package com.iclient.web.filter;

import java.io.IOException;
import java.util.Map;
import java.util.TreeMap;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;

import com.alibaba.fastjson.JSONObject;
import com.iclient.request.EnhancedHttpRequest;

public class AppendParametersFilter implements Filter{


	
	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		Map<String, String[]> extraParams = new TreeMap<String, String[]>();
		String requestData = request.getParameter("data");
		if(null != requestData){
			JSONObject requestJson = JSONObject.parseObject(requestData);
			for(String key : requestJson.keySet()){
				if("data".equals(key)){
					JSONObject dataJson = requestJson.getJSONObject(key);
					for(String k : dataJson.keySet()){
						extraParams.put(k, new String[]{dataJson.getString(k)});
					}
				}else{
					extraParams.put(key, new String[]{requestJson.getString(key)});
				}
			}
		}
		HttpServletRequest wrappedRequest = new EnhancedHttpRequest((HttpServletRequest) request, extraParams);
		chain.doFilter(wrappedRequest, response);
	}

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
	}
	@Override
	public void destroy() {
	}

}
